package top.stacktrace.order.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;
import top.stacktrace.account.service.AccountDubboService;
import top.stacktrace.book.domain.BookPriceVo;
import top.stacktrace.book.service.BookDubboService;
import top.stacktrace.order.dao.OrderDao;
import top.stacktrace.order.domain.Order;

import java.util.function.Consumer;

@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderDao orderDao;
    @DubboReference
    private BookDubboService bookDubboService;
    @DubboReference
    private AccountDubboService accountDubboService;
    @Autowired
    private StreamBridge streamBridge;

    public Order order(long userid, long bookid){
        Order o = new Order();
        o.setId(IdUtil.getSnowflakeNextIdStr());
        o.setBookid(bookid);
        o.setUserid(userid);
        BookPriceVo bv = bookDubboService.getBookPrice(bookid);
        o.setPrice(bv.getPrice());
        Message<Order> oMessage = MessageBuilder.withPayload(o)
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
                .build();
        streamBridge.send("order-in-0",oMessage);
        //streamBridge.send("notice-in-0",o);
        return o;
    }

    @GlobalTransactional
    public void payForOrder(Order order){
        bookDubboService.deCreaseBookReserve(order.getBookid(),1);
        accountDubboService.payForOrder(order.getUserid(),order.getPrice());
        order.setStatus(Order.PAYED);
        orderDao.saveOrder(order);
//        orderDao.saveOrderFailed(order);
        streamBridge.send("notice-in-0",order);
    }
}
